<?php
/**
 * Created by PhpStorm.
 * User: WenQing
 * Date: 2017/7/25
 * Time: 13:35
 */
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); // HTTP/1.1
header("Range: bytes=0-1");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Pragma: no-cache"); // Date in the past

ini_set("session.save_handler", "redis");
ini_set("session.save_path", "tcp://127.0.0.1:6379");

session_start();
$_SESSION['test2'] = 'test2';

var_dump($_SESSION);

?>

<html>
<body>
<a name="top"></a>

<!--done-->
<div id="home">
    <div id="header">
        <div id="blogTitle">
            <a id="lnkBlogLogo" href="http://www.cnblogs.com/k1995/"><img id="blogLogo" src="/Skins/custom/images/logo.gif" alt="返回主页" /></a>

            <!--done-->
            <h1><a id="Header1_HeaderTitle" class="headermaintitle" href="http://www.cnblogs.com/k1995/">King!</a></h1>
            <h2></h2>




        </div><!--end: blogTitle 博客的标题和副标题 -->
        <div id="navigator">

            <ul id="navList">
                <li></li>
                <li><a id="blog_nav_myhome" class="menu" href="http://www.cnblogs.com/k1995/">首页</a></li>
                <li><a href="http://news.cnblogs.com/">新闻</a></li>
                <li><a id="blog_nav_newpost" class="menu" rel="nofollow" href="https://i.cnblogs.com/EditPosts.aspx?opt=1">新随笔</a></li>
                <li><a id="blog_nav_contact" accesskey="9" class="menu" rel="nofollow" href="https://msg.cnblogs.com/send/King%21">联系</a></li>
                <li><a id="blog_nav_admin" class="menu" rel="nofollow" href="https://i.cnblogs.com/">管理</a></li>
                <li><a id="blog_nav_rss" class="menu" href="http://www.cnblogs.com/k1995/rss">订阅</a>
                    <a id="blog_nav_rss_image" class="aHeaderXML" href="http://www.cnblogs.com/k1995/rss"><img src="//www.cnblogs.com/images/xml.gif" alt="订阅" /></a></li>
            </ul>


            <div class="blogStats">

                <div id="blog_stats">
                    <!--done-->
                    随笔- 2&nbsp;
                    文章- 0&nbsp;
                    评论- 0&nbsp;
                </div>

            </div><!--end: blogStats -->
        </div><!--end: navigator 博客导航栏 -->
    </div><!--end: header 头部 -->

    <div id="main">
        <div id="mainContent">
            <div class="forFlow">

                <div id="post_detail">
                    <!--done-->
                    <div id="topics">
                        <div class = "post">
                            <h1 class = "postTitle">
                                <a id="cb_post_title_url" class="postTitle2" href="http://www.cnblogs.com/k1995/p/5699930.html">PHP解析Http协议</a>
                            </h1>
                            <div class="clear"></div>
                            <div class="postBody">
                                <div id="cnblogs_post_body"><p>本文使用PHP解析Http协议</p>
                                    <p>HTTP协议如下，包含两部分：请求头和请求体，我们主要是解析请求头，获取cookie，get，post等信息。</p>
                                    <div class="cnblogs_Highlighter">
<pre class="brush:html;gutter:true;">HTTP/1.1 200 OK

Date: Sun, 25 Oct 2015 15:43:47 GMT

Server: Apache

Set-Cookie: PHPSESSID=4v2actjf96v614r2kh36380kq6; path=/

Expires: Thu, 19 Nov 1981 08:52:00 GMT

Cache-Control: private

Pragma: no-cache

Vary: Accept-Encoding

Content-Length: 5105

Connection: close

Content-Type: text/html; charset=utf-8


&lt;html&gt;
....
&lt;/html&gt;
</pre>
                                    </div>
                                    <p>　　</p>
                                    <p>分析可知,每一行是以\r\n结束,http响应头header和响应体body是以\r\n\r\n分割，下面通过正则表达式可以提取相关元素。</p>
                                    <p>代码如下。</p>
                                    <div class="cnblogs_Highlighter">
<pre class="brush:php;gutter:true;">/**************测试结束****************************/

/*
*  函数:     parse_http
*  描述:     解析http协议
*/
function parse_http($http)
{
        // 初始化
        $_POST = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES =  array();
        $GLOBALS['HTTP_RAW_POST_DATA'] = '';
        // 需要设置的变量名
        $_SERVER = array (
              'QUERY_STRING' =&gt; '',
              'REQUEST_METHOD' =&gt; '',
              'REQUEST_URI' =&gt; '',
              'SERVER_PROTOCOL' =&gt; '',
              'SERVER_SOFTWARE' =&gt; '',
              'SERVER_NAME' =&gt; '',
              'HTTP_HOST' =&gt; '',
              'HTTP_USER_AGENT' =&gt; '',
              'HTTP_ACCEPT' =&gt; '',
              'HTTP_ACCEPT_LANGUAGE' =&gt; '',
              'HTTP_ACCEPT_ENCODING' =&gt; '',
              'HTTP_COOKIE' =&gt; '',
              'HTTP_CONNECTION' =&gt; '',
              'REMOTE_ADDR' =&gt; '',
              'REMOTE_PORT' =&gt; '0',
        );

        // 将header分割成数组
        list($http_header, $http_body) = explode("\r\n\r\n", $http, 2);
        $header_data = explode("\r\n", $http_header);

        list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ', $header_data[0]);

        unset($header_data[0]);
        foreach($header_data as $content)
        {
            // \r\n\r\n
            if(empty($content))
            {
                continue;
            }
            list($key, $value) = explode(':', $content, 2);
            $key = strtolower($key);
            $value = trim($value);
            switch($key)
            {
                // HTTP_HOST
                case 'host':
                    $_SERVER['HTTP_HOST'] = $value;
                    $tmp = explode(':', $value);
                    $_SERVER['SERVER_NAME'] = $tmp[0];
                    if(isset($tmp[1]))
                    {
                        $_SERVER['SERVER_PORT'] = $tmp[1];
                    }
                    break;
                // cookie
                case 'cookie':
                    $_SERVER['HTTP_COOKIE'] = $value;
                    parse_str(str_replace('; ', '&amp;', $_SERVER['HTTP_COOKIE']), $_COOKIE);
                    break;
                // user-agent
                case 'user-agent':
                    $_SERVER['HTTP_USER_AGENT'] = $value;
                    break;
                // accept
                case 'accept':
                    $_SERVER['HTTP_ACCEPT'] = $value;
                    break;
                // accept-language
                case 'accept-language':
                    $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $value;
                    break;
                // accept-encoding
                case 'accept-encoding':
                    $_SERVER['HTTP_ACCEPT_ENCODING'] = $value;
                    break;
                // connection
                case 'connection':
                    $_SERVER['HTTP_CONNECTION'] = $value;
                    break;
                case 'referer':
                    $_SERVER['HTTP_REFERER'] = $value;
                    break;
                case 'if-modified-since':
                    $_SERVER['HTTP_IF_MODIFIED_SINCE'] = $value;
                    break;
                case 'if-none-match':
                    $_SERVER['HTTP_IF_NONE_MATCH'] = $value;
                    break;
                case 'content-type':
                    if(!preg_match('/boundary="?(\S+)"?/', $value, $match))
                    {
                        $_SERVER['CONTENT_TYPE'] = $value;
                    }
                    else
                    {
                        $_SERVER['CONTENT_TYPE'] = 'multipart/form-data';
                        $http_post_boundary = '--'.$match[1];
                    }
                    break;
            }
        }

        // 需要解析$_POST
        if($_SERVER['REQUEST_METHOD'] === 'POST')
        {
            if(isset($_SERVER['CONTENT_TYPE']) &amp;&amp; $_SERVER['CONTENT_TYPE'] === 'multipart/form-data')
            {
                parse_upload_files($http_body, $http_post_boundary);
            }
            else
            {
                parse_str($http_body, $_POST);
                // $GLOBALS['HTTP_RAW_POST_DATA']
                $GLOBALS['HTTP_RAW_POST_DATA'] = $http_body;
            }
        }

        // QUERY_STRING
        $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
        if($_SERVER['QUERY_STRING'])
        {
            // $GET
            parse_str($_SERVER['QUERY_STRING'], $_GET);
        }
        else
        {
            $_SERVER['QUERY_STRING'] = '';
        }

        // REQUEST
        $_REQUEST = array_merge($_GET, $_POST);

        return array('get'=&gt;$_GET, 'post'=&gt;$_POST, 'cookie'=&gt;$_COOKIE, 'server'=&gt;$_SERVER, 'files'=&gt;$_FILES);
 }

/*
*  函数:     parse_upload_files
*  描述:     解析上传的文件
*/
function parse_upload_files($http_body, $http_post_boundary)
{
        $http_body = substr($http_body, 0, strlen($http_body) - (strlen($http_post_boundary) + 4));
        $boundary_data_array = explode($http_post_boundary."\r\n", $http_body);
        if($boundary_data_array[0] === '')
        {
            unset($boundary_data_array[0]);
        }
        foreach($boundary_data_array as $boundary_data_buffer)
        {
            list($boundary_header_buffer, $boundary_value) = explode("\r\n\r\n", $boundary_data_buffer, 2);
            // 去掉末尾\r\n
            $boundary_value = substr($boundary_value, 0, -2);
            foreach (explode("\r\n", $boundary_header_buffer) as $item)
            {
                list($header_key, $header_value) = explode(": ", $item);
                $header_key = strtolower($header_key);
                switch ($header_key)
                {
                    case "content-disposition":
                        // 是文件
                        if(preg_match('/name=".*?"; filename="(.*?)"$/', $header_value, $match))
                        {
                            $_FILES[] = array(
                                'file_name' =&gt; $match[1],
                                'file_data' =&gt; $boundary_value,
                                'file_size' =&gt; strlen($boundary_value),
                            );
                            continue;
                        }
                        // 是post field
                        else
                        {
                            // 收集post
                            if(preg_match('/name="(.*?)"$/', $header_value, $match))
                            {
                                $_POST[$match[1]] = $boundary_value;
                            }
                        }
                        break;
                }
            }
        }
}
</pre>
                                    </div>
                                    <p>注意现在$_POST，$_GET，$_COOKIE，$_REQUEST，$_SESSION，$_FILES都是我们自己通过协议解析到的，而非PHP给我们提供的。</p>
                                    <p>　测试代码下：</p>
                                    <div class="cnblogs_code">
<pre>$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'<a href="http://githubs.cn">http://githubs.cn</a>'<span>);
curl_setopt($ch,CURLOPT_HEADER,1<span>);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1<span>);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,0); //抓取转跳
$output = curl_exec($ch<span>);
curl_close($ch<span>);
var_dump(parse_http($output));</span></span></span></span></span></pre>
                                    </div>
                                    <p>&nbsp;</p></div><div id="MySignature"></div>
                                <div class="clear"></div>
                                <div id="blog_post_info_block">
                                    <div id="BlogPostCategory"></div>
                                    <div id="EntryTag"></div>
                                    <div id="blog_post_info">
                                    </div>
                                    <div class="clear"></div>
                                    <div id="post_next_prev"></div>
                                </div>


                            </div>
                            <div class = "postDesc">posted @ <span id="post-date">2016-07-24 00:22</span> <a href='http://www.cnblogs.com/k1995/'>King!</a> 阅读(<span id="post_view_count">...</span>) 评论(<span id="post_comment_count">...</span>)  <a href ="https://i.cnblogs.com/EditPosts.aspx?postid=5699930" rel="nofollow">编辑</a> <a href="#" onclick="AddToWz(5699930);return false;">收藏</a></div>
                        </div>
                        <script type="text/javascript">var allowComments=true,cb_blogId=250758,cb_entryId=5699930,cb_blogApp=currentBlogApp,cb_blogUserGuid='4ce705fc-11c9-e311-8d02-90b11c0b17d6',cb_entryCreatedDate='2016/7/24 0:22:00';loadViewCount(cb_entryId);</script>

                    </div><!--end: topics 文章、评论容器-->
                </div><a name="!comments"></a><div id="blog-comments-placeholder"></div><script type="text/javascript">var commentManager = new blogCommentManager();commentManager.renderComments(0);</script>
                <div id='comment_form' class='commentform'>
                    <a name='commentform'></a>
                    <div id='divCommentShow'></div>
                    <div id='comment_nav'><span id='span_refresh_tips'></span><a href='javascript:void(0);' onclick='return RefreshCommentList();' id='lnk_RefreshComments' runat='server' clientidmode='Static'>刷新评论</a><a href='#' onclick='return RefreshPage();'>刷新页面</a><a href='#top'>返回顶部</a></div>
                    <div id='comment_form_container'></div>
                    <div class='ad_text_commentbox' id='ad_text_under_commentbox'></div>
                    <div id='ad_t2'></div>
                    <div id='opt_under_post'></div>
                    <div id='cnblogs_c1' class='c_ad_block'></div>
                    <div id='under_post_news'></div>
                    <div id='cnblogs_c2' class='c_ad_block'></div>
                    <div id='under_post_kb'></div>
                    <div id='HistoryToday' class='c_ad_block'></div>
                    <script type='text/javascript'>
                        fixPostBody();
                        setTimeout(function () { incrementViewCount(cb_entryId); }, 50);
                        deliverAdT2();
                        deliverAdC1();
                        deliverAdC2();
                        loadNewsAndKb();
                        loadBlogSignature();
                        LoadPostInfoBlock(cb_blogId, cb_entryId, cb_blogApp, cb_blogUserGuid);
                        GetPrevNextPost(cb_entryId, cb_blogId, cb_entryCreatedDate);
                        loadOptUnderPost();
                        GetHistoryToday(cb_blogId, cb_blogApp, cb_entryCreatedDate);
                    </script>
                </div>


            </div><!--end: forFlow -->
        </div><!--end: mainContent 主体内容容器-->

        <div id="sideBar">
            <div id="sideBarMain">

                <!--done-->
                <div class="newsItem">
                    <h3 class="catListTitle">公告</h3>
                    <div id="blog-news"></div><script type="text/javascript">loadBlogNews();</script>
                </div>

                <div id="calendar"><div id="blog-calendar" style="display:none"></div><script type="text/javascript">loadBlogDefaultCalendar();</script></div>

                <DIV id="leftcontentcontainer">
                    <div id="blog-sidecolumn"></div><script type="text/javascript">loadBlogSideColumn();</script>
                </DIV>

            </div><!--end: sideBarMain -->
        </div><!--end: sideBar 侧边栏容器 -->
        <div class="clear"></div>
    </div><!--end: main -->
    <div class="clear"></div>
    <div id="footer">

        <!--done-->
        Copyright &copy;2017 King!
    </div><!--end: footer -->
</div><!--end: home 自定义的最大容器 -->
<!--PageEndHtml Block Begin-->
<center>友情链接：<a href="http://pan.ibying.com/">百度云盘搜索引擎</a> | <a href="http://www.ibying.com/">BT磁力搜索</a> | <a href="http://www.githubs.cn/">Github中文交流社区</a></center>
<br>
<!--PageEndHtml Block End-->
</body>

</html>
